'''
Created on Oct 6, 2010

@author: oabalbin
'''

from collections import defaultdict, deque
from RNAseq.common.ordereddict import OrderedDict

def get_flow_cell_info(sampleInfoFile,flowCellInfo):
    
    sampleType,tissueType,QC=flowCellInfo[0],flowCellInfo[1],flowCellInfo[2]
    sampleDict = defaultdict(list)    
    for line in sampleInfoFile:
        fields = line.strip('\t\n').split('\t')
        print fields
        if sampleType==fields[4] and tissueType==fields[5] and QC==fields[12]:
            sampleDict[fields[0]] = fields[1:]
    
    return sampleDict


def get_flow_cell_info_all(sampleInfoFile):
    
    #sampleType,tissueType,QC=flowCellInfo[0],flowCellInfo[1],flowCellInfo[2]
    sampleDict = defaultdict(list)    
    for line in sampleInfoFile:
        fields = line.strip('\t\n').split('\t')
        #print fields
        sampleDict[fields[0]] = fields[1:]
    
    return sampleDict

def get_all_samples(sampleInfoFile):
    
    #sampleType,tissueType,QC=flowCellInfo[0],flowCellInfo[1],flowCellInfo[2]
    sampleDict = defaultdict(list)    
    for line in sampleInfoFile:
        fields = line.strip('\t\n').split('\t')
        sampleinfo = fields[16]
        sampleDict[fields[2]] = sampleinfo
        #print fields
        #sampleDict[fields[0]] = fields[1:]
    
    return sampleDict



def get_sample_info(sampleInfoFile,flowCellInfo=[]):
    
    if not flowCellInfo:
        return get_all_samples(sampleInfoFile)
    
    sampleType,tissueType,QC=flowCellInfo[0],flowCellInfo[1],flowCellInfo[2]
    sampleDict = defaultdict(list)
        
    for line in sampleInfoFile:
        fields = line.strip('\t\n').split('\t')
        if sampleType==fields[4] and tissueType==fields[5]:
            if QC and QC==fields[12]:                
                sampleinfo = fields[16].split(' ')[0]    # Split the sample type to get only the initial word (Benign, Localized, Metastatic)
                sampleDict[fields[2]] = sampleinfo
            else:
                sampleinfo = fields[16]
                sampleDict[fields[2]] = sampleinfo

    return sampleDict

def get_header_info(fileh, header_cols=2):
    
    header = fileh.next()
    fields = header.rstrip().split('\t')
    col_names = fields[0:header_cols]
    sample_names = fields[header_cols:]
    params = {}
    for line in fileh:
        fields = line.rstrip().split('\t')
        if fields[0] != '':
            # end of params header
            break
        else:
            params[fields[1]] = fields[header_cols:]
    # return the fields from the last line read
    return fields, col_names, sample_names, params

    

def generate_sample_lists(sample_dict):
    """
    it generates sample lists.
    """
    sample_lists=defaultdict(list)
    benign, localized, met = 'Benign', 'Localized', 'Metastatic' 
    for sp, sptype in sample_dict.iteritems():
        if sptype == benign:
            sample_lists['Benign'].append(sp)
        elif sptype == localized:
            sample_lists[localized].append(sp)
        elif sptype == met:
            sample_lists[met].append(sp)
        else:
            continue
    return sample_lists


def split_samples_TumorvsBening(sample_dict):
    
    normal_samples_list,thissampleslist=[],[]
    for sptype, sps in sample_dict.iteritems():
        if sptype=='Benign':
            sps.sort()
            normal_samples_list = sps
        else:
            sps.sort()
            thissampleslist.append(sps)
    
    thissampleslist=sum(thissampleslist,[])
    
    return thissampleslist, normal_samples_list


def get_sample_columns(mysample_dict, all_samples):
    '''
    Returns a dictionary with the new_matrix_index:sample.
    A list with all sample indexes
    A list with benign samples indexes
    '''
    
    sample_subset = OrderedDict()
    sample_subset2 = OrderedDict()
    sp_columns_in_allsamples = deque()
    benign_columns_in_allsamples = deque()
    j=0
    for sptype, samplelist in mysample_dict.iteritems():
        if sptype=='Benign':
            samplelist.sort()
            for sp in  samplelist:
                
                try:
                    sp_columns_in_allsamples.append(all_samples[sp])
                    benign_columns_in_allsamples.append(j)
                    sample_subset[j] = sp
                    sample_subset2[sp] = j
                    j+=1
                except KeyError:
                    print 'sample not found ', sp, j
        else:
            samplelist.sort()
            for sp in  samplelist:
                try:
                    sp_columns_in_allsamples.append(all_samples[sp])
                    sample_subset[j] = sp
                    j+=1
                except KeyError:
                    print 'sample not found ', sp, j
            
    return sample_subset, sp_columns_in_allsamples, benign_columns_in_allsamples


def read_library_statistics(inputfile_name):
    '''
    It reads a processed file with the sample statistics. This file is obtained by running
     python ~/workspace/LibraryQuality/trunk/LibraryQuality/sample_parameter_collection.py
    It returns a dictionary with library properties and list of pairs (flowcell,value)
    statistics: UNMAPPED_READS, ESTIMATED_LIBRARY_SIZE, UNPAIRED_READS_EXAMINED, READ_PAIRS_EXAMINED
    READ_PAIR_OPTICAL_DUPLICATES, PERCENT_DUPLICATION, LIBRARY, READ_PAIR_DUPLICATES, UNPAIRED_READ_DUPLICATES
    '''
    inputfile = open(inputfile_name)
    header = inputfile.next().strip('\n').split('\t')[1:]
    library_statistics=defaultdict(deque)
    for line in inputfile:
        fields =line.strip('\n').split('\t')
        library_statistics[fields[0]]= [(sp, vl) for sp, vl in zip(header,fields[1:])]
        print library_statistics[fields[0]]
    return library_statistics
    inputfile.close()
    

def sample_library_statistic(samplestatics):
    '''
    returns a dict of sample name: statistcs
    '''
    spstats = defaultdict()
    for field in samplestatics:
        spname = field[0].split('_')[-2]
        value = field[1]
        spstats[spname] = value
    
    return spstats
    
    
    
